package com.example.myapp.Activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.User;
import com.example.myapp.R;

import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class EditUser extends AppCompatActivity {
    private static final int REQUEST_CODE_PICK_IMAGE = 1;//相册入口
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 2;//打开相机入口
    private static final int RESIZE_REQUEST_CODE = 3;//裁剪图片入口
    LinearLayout editicon;
    LinearLayout edit_username;
    LinearLayout edit_sex;
    LinearLayout edit_place;
    LinearLayout edit_email;
    LinearLayout edit_brith;
    CircleImageView edit_image;
    TextView eidtshow_username;
    TextView eidtshow_sex;
    TextView eidtshow_place;
    TextView eidtshow_show;
    TextView eidtshow_email;
    TextView  eidtshow_brith;
    private String url="http://pybchat.justwen233.cn/upadtaUser";
    private Calendar cal;
    private int year, month, day;
    private MyData myData;
    private Uri userImageUri;//切图后图片的路径
    private  String upIconurl;
    private  ShapeLoadingDialog shapeLoadingDialog;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {

                    upimage(upIconurl);
                    break;
                }
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);

        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_edituser);
        ImageView  edituser_back=findViewById(R.id.edituser_back);
        editicon=findViewById(R.id.editicon);
        edit_username=findViewById(R.id.edit_username);
        edit_sex=findViewById(R.id.edit_sex);
        edit_place=findViewById(R.id.edit_place);
        edit_email=findViewById(R.id.edit_email);
        edit_image=findViewById(R.id.edit_image);

        eidtshow_username=findViewById(R.id.eidtshow_username);
        eidtshow_sex=findViewById(R.id.eidtshow_sex);
        eidtshow_place=findViewById(R.id.eidtshow_place);
        eidtshow_email=findViewById(R.id.eidtshow_email);
        eidtshow_show=findViewById(R.id.eidtshow_show);
        eidtshow_brith=findViewById(R.id.eidtshow_brith);
        edit_brith=findViewById(R.id.edit_brith);
        myData= (MyData)getApplication();
        judgePermission();
        init();//页面初始化（用的事myData的数据）

        edit_username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username_dialog(v);
            }
        });//编辑用户名
        edit_brith.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDate();//获取当前时间日期
                DatePickerDialog.OnDateSetListener listener=new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        ++month;
                        //月份默认少一个月
                        eidtshow_brith.setText(year + "-" + month + "-" + dayOfMonth);
                         if (month<10){
                             if(dayOfMonth<10) {
                                 eidtshow_brith.setText(year + "-" + "0"+month + "-" + "0"+dayOfMonth);
                             }else {
                                 eidtshow_brith.setText(year + "-" + month + "-" + dayOfMonth);
                             }
                         }else {
                             if(dayOfMonth<10){
                                 eidtshow_brith.setText(year + "-" + month + "-" + "0"+dayOfMonth);
                             }
                             else {
                                 eidtshow_brith.setText(year + "-" + month + "-" + dayOfMonth);
                             }
                         }

                    }
                };
                DatePickerDialog dialog=new DatePickerDialog(EditUser.this, DatePickerDialog.THEME_HOLO_LIGHT,
                        listener,year,month,day);
                //主题在这里！后边三个参数为显示dialog时默认的日期，月份从0开始，0-11对应1-12个月
                dialog.show();

                User user =new User();
                user.setBirth(eidtshow_brith.getText().toString());
                user.update(myData.getObjID(), new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            Log.w("aaaa", "更改生日成功" );
                            myData.setBirth(eidtshow_brith.getText().toString());
                        } else {
                            Log.w("aaaa", "更改数据失败：" + e.getMessage());
                            Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                        }
                    }
                });

            }
        });//编辑生日
        edit_sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sex_dialog(v);
            }
        });//编辑性别
        edit_place.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                place_dialog(v);
            }
        });//编辑户籍
        edit_email.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email_dialog(v);
            }
        });//编邮箱
        edituser_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });//back
        //选择上传方式（拍照+相册）
        editicon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                judgePermission();//判断权限

                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);//设置入口

            }

        });//编辑头像


        //文本框监听开始，判断昵称是否被占用
        TextWatcher watcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Toast.makeText(getApplicationContext(), "输入之前", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Toast.makeText(getApplicationContext(), "在输入中", Toast.LENGTH_SHORT).show();


            }
            @Override
            public void afterTextChanged(Editable s) {
                User user =new User();
                user.setShow(eidtshow_show.getText().toString());
                user.update(myData.getObjID(), new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            Log.w("aaaa", "更改成功" );
                            myData.setShow(eidtshow_show.getText().toString());
                        } else {
                            Log.w("aaaa", "更改数据失败：" + e.getMessage());
                            Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        };
        eidtshow_show.addTextChangedListener(watcher);
        //文本框监听结束
    }
    @Override
    public void onBackPressed() {
        //此处写退向后台的处理
        finish();
        Log.w("aaaa","我点击返回键！");
    }//手机返回键
    //    响应函数
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //结果码不等于取消时候

        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case REQUEST_CODE_PICK_IMAGE://使用本地相册获取头像
                {
                    if (data != null) {
                        // 得到图片的全路径
                        userImageUri= data.getData();
                        Log.w("aaaa", "原文件地址(上传的)"+ getRealPathFromUri(EditUser.this,userImageUri));
                        reSizeImage(getRealPathFromUri(EditUser.this,userImageUri));
                    }
                    break;
                }
                case RESIZE_REQUEST_CODE://剪切得到的图片
                {
                    if (data != null) {
                        // 得到图片的全路径
                        userImageUri= data.getData();
                        showimage(userImageUri);
                    }
                    break;
                }

            }
        }
    }
    private void reSizeImage(String imagePath) {
        File file = new File(Environment.getExternalStorageDirectory(), "/PYB/upicon.jpg");
        upIconurl = file.getAbsolutePath();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 000);
        intent.putExtra("scale", 300);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }

    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }


    //显示照片
    private void showimage(Uri uri){

                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
    }

//    上传头像
   private void upimage(String iconpath){
       Log.w("aaaa", "实际上传路径"+iconpath);
       openLoading();
       final BmobFile bmobFile = new BmobFile(new File(iconpath));
       bmobFile.uploadblock(new UploadFileListener() {
           @Override
           public void done(BmobException e) {
               if (e == null) {
                   Log.w("aaaa", "上传素材成功！");
                   User user = new User();
                   user.setIcon(bmobFile);
                   user.update( myData.getObjID(), new UpdateListener() {
                       @Override
                       public void done(BmobException e) {
                           if (e == null) {
                               Log.w("aaaa", "更改成功" );
                               Glide.with(EditUser.this).load(bmobFile.getUrl()).into(edit_image);
                                myData.setIconUrl(bmobFile.getUrl());
                               Chatusername(myData.getObjID(),myData.getUserName(),bmobFile.getUrl());
                               closeLoading();
                           } else {
                               Log.w("aaaa", "更改数据失败：" + e.getMessage());
                               Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                           }
                       }
                   });
               } else {
                   Log.w("aaaa", "上传素材失败：" + e.getMessage());
               }
           }
           @Override
           public void onProgress(Integer value) {
               // 返回的上传进度（百分比）
           }
       });

   }

    //编辑用户名
    public void username_dialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(EditUser.this);
        // 通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        final   EditText et =new EditText(EditUser.this);
        builder.setView(et);
        builder.setTitle("请输入用户名");
        builder.setView(et);
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(et.getText().toString().trim().length()==0){
                            return;
                        }
                        final String[] objectId = new String[1];
                        BmobQuery<User> query = new BmobQuery<User>();
                        query.addWhereEqualTo("username",et.getText().toString());//字段名，Phone
                        query.findObjects(new FindListener<User>() {
                            @Override
                            public void done(List<User> list, BmobException e) {
                                if (e==null){

                                    //获取ObjectId
                                    for(User userl:list){ objectId[0]  =userl.getObjectId();}
                                    if(objectId[0]!=null ){
                                        Toast.makeText(EditUser.this, "该昵称已经被占用，请重试！", Toast.LENGTH_LONG).show();
                                        eidtshow_username.setText(myData.getUserName());
                                    } else{
                                        eidtshow_username.setText(et.getText().toString());
                                        User user =new User();
                                        user.setUsername(et.getText().toString());
                                        user.update(myData.getObjID(), new UpdateListener() {
                                            @Override
                                            public void done(BmobException e) {
                                                if (e == null) {
                                                    Log.w("aaaa", "更改用户名成功" );
                                                    myData.setUserName(eidtshow_username.getText().toString());
                                                    Chatusername(myData.getObjID(),myData.getUserName(),myData.getIconUrl());
                                                } else {
                                                    Log.w("aaaa", "更改数据失败：" + e.getMessage());
                                                    Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        });
                                    }
                                }else {
                                    Toast.makeText(EditUser.this, "系统出错请稍后重试", Toast.LENGTH_LONG).show();
                                }
                            }
                        });


                    }
                });

        builder.show();
    }



    //编辑聊天用户名
    private  void Chatusername(String objectId,String username,String icon){
            Map<String,String> map=new HashMap<String,String>();
            map.put("objectId",objectId);
            map.put("username", username);
            map.put("icon", icon);
            JSONObject params=new JSONObject(map);
            RequestQueue requestQueue2 = Volley.newRequestQueue(EditUser.this);
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new com.android.volley.Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.w("vivi", "onResponse: "+ response);

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                    Log.d("vivi", "error: " + error.getMessage());

                }
            });
            //添加队列
            requestQueue2.add(jsonObjectRequest);
            requestQueue2.cancelAll(this);


    }





    //选择性别
    public void sex_dialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(EditUser.this);
        final String[] items = {"男", "女", "保密"};
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                eidtshow_sex.setText(items[which]);
                User user =new User();
                user.setSex(items[which]);
                user.update(myData.getObjID(), new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            Log.w("aaaa", "更改性别成功" );
                            myData.setSex(items[which]);
                        } else {
                            Log.w("aaaa", "更改数据失败：" + e.getMessage());
                            Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
        builder.show();
    }
    //编辑户籍
    public void place_dialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(EditUser.this);
        // 通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        final   EditText et =new EditText(EditUser.this);
        builder.setView(et);
         builder.setTitle("请输入户籍");
         builder.setView(et);
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(et.getText().toString().trim().length()==0){
                            return;
                        }
                        eidtshow_place.setText(et.getText().toString());
                        User user =new User();
                        user.setBirthPlace(et.getText().toString());
                        user.update(myData.getObjID(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    Log.w("aaaa", "更改户籍成功" );
                                    myData.setBirthPlace(eidtshow_place.getText().toString());
                                } else {
                                    Log.w("aaaa", "更改数据失败：" + e.getMessage());
                                    Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                                }
                            }
                        });

                    }
                });

        builder.show();
    }
//    编辑邮箱
    public void email_dialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(EditUser.this);
        // 通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        final   EditText et =new EditText(EditUser.this);
        builder.setTitle("请输入邮箱");
        builder.setView(et);
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if(et.getText().toString().trim().length()==0){
                            return;
                        }
                        if(isEmail(et.getText().toString())){
                             eidtshow_email.setText(et.getText().toString());
                            User user =new User();
                            user.setMobilePhoneNumberVerified(true);
                            user.setMyEamil(eidtshow_email.getText().toString());
                            user.update(myData.getObjID(), new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        Log.w("aaaa", "更改邮箱成功" );
                                        myData.setEmail(eidtshow_email.getText().toString());
                                    } else {
                                        Log.w("aaaa", "更改数据失败：" + e.getMessage());
                                        Toast.makeText(EditUser.this, "服务器出错！" , Toast.LENGTH_LONG).show();
                                    }
                                }
                            });

                        }
                        else {
                            Toast.makeText(EditUser.this,"你输入邮箱有误请重试！" , Toast.LENGTH_LONG).show();
                        }
                    }
                });

        builder.show();
    }
    //页面初始化
    private  void init(){
        String username=myData.getUserName();
        eidtshow_username.setText(username);
        eidtshow_sex.setText(myData.getSex());
        eidtshow_brith.setText(myData.getBirth());
        eidtshow_place.setText(myData.getBirthPlace());
        eidtshow_email.setText(myData.getEmail());
        eidtshow_show.setText(myData.getShow());
        Glide.with(EditUser.this).load(myData.getIconUrl()).into(edit_image);

    }
  //    验证邮箱格式
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        String telRegex = strPattern;
        if (TextUtils.isEmpty(strEmail)){
            return false;
        }
        else return strEmail.matches(telRegex);
    }
    //获取当前日期
    private void getDate() {
        cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);       //获取年月日时
        month = cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day = cal.get(Calendar.DAY_OF_MONTH);
    }
    //将contenUri转为String真实路径
    private String getImagePath(Uri uri, String seletion) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, seletion, null, null);
        if (cursor != null) {
            //将光标移至开头 ，这个很重要，不小心很容易引起越界
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //    绝对路径--》》contentUri开始
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }



    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    //获取app做需要的权限
    protected void judgePermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝

            // sd卡权限
            String[] SdCardPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, SdCardPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCardPermission, 100);
            }

        }
    }

    //网络加载
    private void openLoading() {
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(EditUser.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }

    //关闭网络加载
    private void closeLoading() {
        shapeLoadingDialog.dismiss();
    }

}
